package com.xiaobai.DeadLock;

import com.xiaobai.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
/*
死锁
 */
@Slf4j
public class DeadLock {
    public static void main(String[] args) {
        Object A = new Object();
        Object B = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (A) {
                log.debug("lock A");
                ThreadUtil.sleep(2);
                synchronized (B) {
                    log.debug("lock B");
                    log.debug("操作...");
                }
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            synchronized (B) {
                log.debug("lock B");
                ThreadUtil.sleep(1);
                synchronized (A) {
                    log.debug("lock A");
                    log.debug("操作...");
                }
            }
        }, "t2");
        t1.start();
        t2.start();
    }
}
/*
1.通过jstack来进行定位
Found one Java-level deadlock:
=============================
"t1":
  waiting to lock monitor 0x000001f6cd2eba70 (object 0x00000007138b51e8, a java.lang.Object),
  which is held by "t2"

"t2":
  waiting to lock monitor 0x000001f6cd2eb450 (object 0x00000007138b51d8, a java.lang.Object),
  which is held by "t1"

Java stack information for the threads listed above:
===================================================
"t1":
        at com.xiaobai.DeadLock.DeadLock.lambda$main$0(DeadLock.java:18)
        - waiting to lock <0x00000007138b51e8> (a java.lang.Object)
        - locked <0x00000007138b51d8> (a java.lang.Object)
        at com.xiaobai.DeadLock.DeadLock$$Lambda$30/0x000001f68901cf28.run(Unknown Source)
        at java.lang.Thread.run(java.base@17.0.14/Thread.java:842)
"t2":
        at com.xiaobai.DeadLock.DeadLock.lambda$main$1(DeadLock.java:28)
        - waiting to lock <0x00000007138b51d8> (a java.lang.Object)
        - locked <0x00000007138b51e8> (a java.lang.Object)
        at com.xiaobai.DeadLock.DeadLock$$Lambda$31/0x000001f68901d148.run(Unknown Source)
        at java.lang.Thread.run(java.base@17.0.14/Thread.java:842)

Found 1 deadlock.


2.通过用jconsole.exe来进行观察 在线程里面有个检测死锁的
 */
